<template>
  <view class="container">
    <view class="left-bottom-sign"></view>
    <view class="back-btn yticon icon-zuojiantou-up" @click="navBack"></view>
    <view class="right-top-sign"></view>
    <!-- 设置白色背景防止软键盘把下部绝对定位元素顶上来盖住输入框等 -->
    <view class="wrapper">
      <view class="left-top-sign">LOGIN</view>
      <view class="welcome">欢迎回来！</view>
      <view class="input-content">
        <view class="input-item">
          <text class="tit">手机号码</text>
          <input
              type="number"
              :value="phone"
              placeholder="请输入手机号码"
              maxlength="11"
              data-key="phone"
              @input="inputChange"
          />
        </view>
        <view class="input-item">
          <text class="tit">密码</text>
          <input
              type="password"
              :value="password"
              placeholder="请输入6位以上密码"
              maxlength="20"
              data-key="password"
              @input="inputChange"
              @confirm="toLogin"
          />
        </view>
      </view>
      <button class="confirm-btn" @click="toLogin" :disabled="logining">
        {{ logining ? '登录中...' : '登录' }}
      </button>
      <view class="forget-section" @click="toForgetPassword">忘记密码?</view>
    </view>
    <view class="register-section">
      还没有账号?
      <text @click="toRegist">马上注册</text>
    </view>
  </view>
</template>

<script>
import { mapMutations } from 'vuex';

export default {
  data() {
    return {
      phone: '',
      password: '',
      logining: false
    };
  },
  onLoad() {
    // 页面加载时检查是否已有token
    const token = uni.getStorageSync('token');
    if (token) {
      this.validateToken(token);
    }
  },
  methods: {
    ...mapMutations(['login']),
    inputChange(e) {
      const key = e.currentTarget.dataset.key;
      this[key] = e.detail.value;
    },
    navBack() {
      uni.navigateBack();
    },
    toRegist() {
      uni.navigateTo({
        url: '/pages/register/register'
      });
    },
    toForgetPassword() {
      uni.navigateTo({
        url: '/pages/forget-password/forget-password'
      });
    },
    async validateToken(token) {
      try {
        const [err, res] = await uni.request({
          url: 'http://localhost:8080/app/user/validate-token', // 修正为你的后端接口路径
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}` // 添加 Bearer 前缀
          }
        });
        if (res.data.code === 200) {
          // token有效，直接跳转到首页
          uni.redirectTo({url: '/pages/index/index'});
        } else {
          // token无效，清除存储并留在登录页面
          uni.removeStorageSync('token');
          uni.removeStorageSync('userInfo');
        }
      } catch (error) {
        console.error('Token validation failed:', error);
        uni.removeStorageSync('token');
        uni.removeStorageSync('userInfo');
      }
    },
    async toLogin() {
      if (!this.phone) {
        uni.showToast({title: '请输入手机号码', icon: 'none'});
        return;
      }
      if (!/^\d{11}$/.test(this.phone)) {
        uni.showToast({title: '请输入有效的11位手机号码', icon: 'none'});
        return;
      }
      if (!this.password) {
        uni.showToast({title: '请输入密码', icon: 'none'});
        return;
      }
      if (this.password.length < 6) {
        uni.showToast({title: '密码长度不能少于6位', icon: 'none'});
        return;
      }

      this.logining = true;
      try {
        const [err, res] = await uni.request({
          url: 'http://localhost:8080/app/user/login',
          method: 'POST',
          header: {
            'Content-Type': 'application/json'
          },
          data: {
            phone: this.phone,
            password: this.password
          }
        });

        console.log('登录响应:', res);

        if (res.data.code === 200) {
          const result = res.data.data;
          const userInfo = {
            id: result.userInfo.id,
            phone: result.userInfo.phone,
            username: result.userInfo.username,
            nickname: result.userInfo.nickname || result.userInfo.username || result.userInfo.phone // 使用 phone 作为默认昵称
          };
          uni.setStorageSync('token', result.token);
          uni.setStorageSync('userInfo', userInfo);
          console.log('保存的 userInfo:', userInfo);
          this.login(userInfo);
          uni.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 1500
          });
          console.log('准备跳转到首页');
          uni.reLaunch({
            url: '/pages/index/index',
            success: () => console.log('跳转成功'),
            fail: (err) => console.error('跳转失败:', err)
          });
        } else {
          uni.showToast({
            title: res.data.msg || '登录失败，请稍后重试',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('登录请求异常:', error);
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      } finally {
        this.logining = false;
      }
    }
  }
};
</script>

<style lang="scss">
page {
  background: #fff;
}

.container {
  padding-top: 115px;
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: #fff;
}

.wrapper {
  position: relative;
  z-index: 90;
  background: #fff;
  padding-bottom: 40upx;
}

.back-btn {
  position: absolute;
  left: 40upx;
  z-index: 9999;
  padding-top: var(--status-bar-height);
  top: 40upx;
  font-size: 40upx;
  color: $font-color-dark;
}

.left-top-sign {
  font-size: 120upx;
  color: $page-color-base;
  position: relative;
  left: -16upx;
}

.right-top-sign {
  position: absolute;
  top: 80upx;
  right: -30upx;
  z-index: 95;

  &:before,
  &:after {
    display: block;
    content: '';
    width: 400upx;
    height: 80upx;
    background: #b4f3e2;
  }

  &:before {
    transform: rotate(50deg);
    border-radius: 0 50px 0 0;
  }

  &:after {
    position: absolute;
    right: -198upx;
    top: 0;
    transform: rotate(-50deg);
    border-radius: 50px 0 0 0;
  }
}

.left-bottom-sign {
  position: absolute;
  left: -270upx;
  bottom: -320upx;
  border: 100upx solid #d0d1fd;
  border-radius: 50%;
  padding: 180upx;
}

.welcome {
  position: relative;
  left: 50upx;
  top: -90upx;
  font-size: 46upx;
  color: #555;
  text-shadow: 1px 0px 1px rgba(0, 0, 0, 0.3);
}

.input-content {
  padding: 0 60upx;
}

.input-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  padding: 0 30upx;
  background: $page-color-light;
  height: 120upx;
  border-radius: 4px;
  margin-bottom: 50upx;

  &:last-child {
    margin-bottom: 0;
  }

  .tit {
    height: 50upx;
    line-height: 56upx;
    font-size: $font-sm + 2upx;
    color: $font-color-base;
  }

  input {
    height: 60upx;
    font-size: $font-base + 2upx;
    color: $font-color-dark;
    width: 100%;
  }
}

.confirm-btn {
  width: 630upx;
  height: 76upx;
  line-height: 76upx;
  border-radius: 50px;
  margin-top: 70upx;
  background: $uni-color-primary;
  color: #fff;
  font-size: $font-lg;

  &:after {
    border-radius: 100px;
  }
}

.forget-section {
  font-size: $font-sm + 2upx;
  color: $font-color-spec;
  text-align: center;
  margin-top: 40upx;
}

.register-section {
  position: absolute;
  left: 0;
  bottom: 50upx;
  width: 100%;
  font-size: $font-sm + 2upx;
  color: $font-color-base;
  text-align: center;

  text {
    color: $font-color-spec;
    margin-left: 10upx;
  }
}
</style>